package cn.hinglo.gameclaw.im.service;

import cn.hinglo.gameclaw.im.utils.HttpClientUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static cn.hinglo.gameclaw.im.utils.HttpClientUtils.getCode;
import static cn.hinglo.gameclaw.im.utils.HttpClientUtils.getResult;


/**
 * @createTime: 2018/3/6
 * @author: HingLo
 * @description: 通讯管理的服务层
 */
@Service
public class ImService {
    private static final String URL = "https://api.netease.im/nimserver/";

    public static void main(String[] args) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("accid", "admin");
        param.put("name", "admin");
        param.put("token", "gameclawforkeji.com");
        String result = HttpClientUtils.postFormData(URL + "user/create.action", param, false);
        System.out.println(result);

    }

    /**
     * 创建云信Id
     *
     * @param id   三方登录的唯一用户Id
     * @param name 设置昵称
     * @return 返回同步后的唯一token，用户与云信交互认证
     */
    public String createAccIdService(String id, String name) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("accid", id);
        param.put("name", name);
        String result = HttpClientUtils.postFormData(URL + "user/create.action", param, false);
        return getResult(result, "info.token");
    }

    /**
     * 如果登录用户的token丢失，用户此方法来刷新token
     *
     * @param accId 三方登录的唯一Id
     * @return 更新后的token
     */
    public String updateToken(String accId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("accid", accId);
        String result = HttpClientUtils.postFormData(URL + "user/refreshToken.action", param, false);
        if (getCode(result)) {
            return (String) getResult(result, "info.token");
        }
        return null;
    }

    /**
     * 更新用户的昵称
     *
     * @param accId 云信的ID
     * @param name  需要更新的昵称
     * @return 返回更新结果
     */
    public boolean updateNickname(String accId, String name) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("accid", accId);
        param.put("name", name);
        String result = HttpClientUtils.postFormData(URL + "user/updateUserinfo.action", param, false);
        return getCode(result);
    }
}
